package tech.aistar.service.impl;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import tech.aistar.constants.RedisConstant;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AsyncService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送邮箱注册验证码
     * @param to
     * @throws InterruptedException
     */
    @Async
    public void sendMailCode(String to,String keyName){
        String code = RandomUtil.randomNumbers(6);
        log.info("{}-code:{}", to,code);
        stringRedisTemplate.opsForValue().set(
                keyName + to,
                code,
                3,
                TimeUnit.MINUTES
        );
        //构造信息
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom("3196287362@qq.com");
        mailMessage.setSubject("青岛科技大学验证码");
        mailMessage.setText("验证码：" + code);
        mailMessage.setTo(to);
        //发送消息
        mailSender.send(mailMessage);
    }
}
